﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QThread>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::ReadAllData);
    connect(tcpSocket,&QTcpSocket::connected,this,&MainWindow::Connected);
    connect(tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::Disconnected);
    connect(tcpSocket,&QTcpSocket::stateChanged,this,&MainWindow::StateChanged);
    address = QHostAddress("127.0.0.1");
    port = 5023;
    ui->txtIp->setText(address.toString());
    ui->txtPort->setText(QString::number(port));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::ReadAllData()
{
    QByteArray buff = tcpSocket->readAll();
    qDebug() << buff;
    ui->txtLog->append(buff);
}

void MainWindow::Connected()
{
    QString address = tcpSocket->peerAddress().toString();
    int port = tcpSocket->peerPort();
    qDebug() << QString("连接成功, %1:%2").arg(address).arg(port);
    ui->txtLog->append(QString("连接成功, %1:%2").arg(address).arg(port));
}

void MainWindow::Disconnected()
{
    QString address = tcpSocket->peerAddress().toString();
    int port = tcpSocket->peerPort();
    qDebug() << QString("断开链接功, %1:%2").arg(address).arg(port);
    ui->txtLog->append(QString("断开链接, %1:%2").arg(address).arg(port));
}

void MainWindow::StateChanged()
{
    if(tcpSocket->state() == QTcpSocket::SocketState::ConnectedState)
    {
        ui->btnDisconnect->setText("断开");
        ui->txtIp->setEnabled(false);
        ui->txtPort->setEnabled(false);
    }
    if(tcpSocket->state() == QTcpSocket::SocketState::UnconnectedState)
    {
//        ui->btnDisconnect->setText("连接");
//        ui->txtIp->setEnabled(true);
//        ui->txtPort->setEnabled(true);
    }
}

void MainWindow::on_btnSend_clicked()
{
    QString txt = ui->txtSend->toPlainText();
    tcpSocket->write(txt.toStdString().c_str());
}

void MainWindow::on_btnDisconnect_clicked()
{
    address = QHostAddress(ui->txtIp->text());
    port = ui->txtPort->text().toInt();
    if(tcpSocket->state() == QTcpSocket::SocketState::ConnectedState)
    {
        tcpSocket->disconnectFromHost();
        if(tcpSocket->state() == QAbstractSocket::UnconnectedState || tcpSocket->waitForDisconnected(3000))
        {
            ui->btnDisconnect->setText("连接");
            ui->txtIp->setEnabled(true);
            ui->txtPort->setEnabled(true);
        }
    }
    else if(tcpSocket->state() == QTcpSocket::SocketState::UnconnectedState)
    {
        tcpSocket->connectToHost(address.toString(),port);
    }
}
